// src/stores/graphStore.js
import { defineStore } from 'pinia';
import axios from 'axios';

const API_BASE_URL = 'http://localhost:3000/api';

// 辅助函数：合并图数据并去重
function mergeGraphData(existing, newData) {
    const nodeIds = new Set(existing.nodes.map(n => n.id));
    const edgeIds = new Set(existing.edges.map(e => e.id));

    newData.nodes.forEach(node => {
        if (!nodeIds.has(node.id)) {
            existing.nodes.push(node);
            nodeIds.add(node.id);
        }
    });

    newData.edges.forEach(edge => {
        if (!edgeIds.has(edge.id)) {
            existing.edges.push(edge);
            edgeIds.add(edge.id);
        }
    });
    return existing;
}

export const useGraphStore = defineStore('graph', {
    state: () => ({
        nodes: [],
        edges: [],
        chatHistory: [
            {
                role: 'ai',
                content: '您好！欢迎使用知识图谱智能问答系统，您可以输入一种桥梁病害名称，而我将会为您查询知识图谱并进行解释。',
                subgraph: null
            }
        ],
        isLoading: false,
    }),
    getters: {
        graphData: (state) => ({ nodes: state.nodes, edges: state.edges }),
        nodeCount: (state) => state.nodes.length,
        edgeCount: (state) => state.edges.length,
        nodeLabels: (state) => {
            const counts = {};
            state.nodes.forEach(node => {
                const label = node._labels ? node._labels[0] : 'default';
                counts[label] = (counts[label] || 0) + 1;
            });
            return counts;
        },
        relationshipTypes: (state) => {
            const counts = {};
            state.edges.forEach(edge => {
                counts[edge.label] = (counts[edge.label] || 0) + 1;
            });
            return counts;
        }
    },
    actions: {
        async fetchInitialGraph() {
            this.isLoading = true;
            try {
                const { data } = await axios.get(`${API_BASE_URL}/initial-graph`);
                this.nodes = data.nodes;
                this.edges = data.edges;
            } catch (error) {
                console.error('Failed to fetch initial graph:', error);
                alert('获取初始图谱失败！');
            } finally {
                this.isLoading = false;
            }
        },
        async expandNode(nodeId) {
            this.isLoading = true;
            try {
                const { data } = await axios.post(`${API_BASE_URL}/expand-node`, { nodeId });
                const currentData = { nodes: this.nodes, edges: this.edges };
                const mergedData = mergeGraphData(currentData, data);
                // 必须重新赋值以触发响应式更新
                this.nodes = [...mergedData.nodes];
                this.edges = [...mergedData.edges];
            } catch (error) {
                console.error('Failed to expand node:', error);
                alert('展开节点失败！');
            } finally {
                this.isLoading = false;
            }
        },
        async askQuestion(question) {
            this.isLoading = true;
            this.chatHistory.push({ role: 'user', content: question });

            try {
                const { data } = await axios.post(`${API_BASE_URL}/ask`, { question, use_kg: true });
                this.chatHistory.push({
                    role: 'ai',
                    content: data.answer,
                    subgraph: data.subgraph,
                    cypher: data.cypher
                });
                // 默认直接显示问答返回的子图
                if (data.subgraph && data.subgraph.nodes) {
                    this.setGraphData(data.subgraph);
                }
            } catch (error) {
                console.error('Failed to ask question:', error);
                const errorMessage = '抱歉，回答问题时出错。';
                this.chatHistory.push({ role: 'ai', content: errorMessage });
                alert(errorMessage);
            } finally {
                this.isLoading = false;
            }
        },
        setGraphData(subgraph) {
            if (subgraph && subgraph.nodes) {
                 // G6 需要 id 是字符串
                this.nodes = subgraph.nodes.map(n => ({...n, id: String(n.id)}));
                this.edges = subgraph.edges.map(e => ({
                    ...e, 
                    id: String(e.id),
                    source: String(e.source),
                    target: String(e.target)
                }));
            }
        }
    },
});